import numpy as np
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
import random
import csv

# 读取数据
sreader = np.zeros((400, 3))
with open('dataset_circles.csv', 'r') as f:
    i = 0
    reader = csv.reader(f)
    for row in reader:
        xreadr = row
        sreader[i, :] = xreadr
        i = i + 1
    X = sreader[:, 0:2]
    y = sreader[:, 2]

# 画出数据
plt.figure(figsize=(15, 9))
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.colorbar()
plt.show()

thita = np.zeros((400, 1))
ro = np.zeros((400, 1))
for i in range(400):
    thita[i] = np.arctan(X[i, 1] / X[i, 0])
    ro[i] = (X[i, 1] ** 2 + X[i, 0] ** 2) ** 0.5
X = np.c_[thita, ro]


def calc_distance(v1, v2):
    return np.sum(np.square(v1 - v2))


def rand_cluster_cents(X, k):
    """初始化聚类中心：通过在区间范围随机产生的值作为新的中心点"""

    # 样本数
    m = np.shape(X)[0]

    # 生成随机下标列表
    dataIndex = list(range(m))
    random.shuffle(dataIndex)
    centroidsIndex = dataIndex[:k]

    # 返回随机的聚类中心
    return X[centroidsIndex, :]


def kmeans(X, k):
    # 样本总数
    m = np.shape(X)[0]

    # 分配样本到最近的簇：存[簇序号,距离的平方] (m行 x 2 列)
    clusterAssment = np.zeros((m, 2))

    # step1: 通过随机产生的样本点初始化聚类中心
    centroids = rand_cluster_cents(X, k)
    print('最初的中心=', centroids)

    iterN = 0

    while True:
        clusterChanged = False

        # step2:分配到最近的聚类中心对应的簇中
        for i in range(m):
            minDist = np.inf;
            minIndex = -1
            for j in range(k):
                # 计算第i个样本到第j个中心点的距离
                distJI = calc_distance(centroids[j, :], X[i, :])
                if distJI < minDist:
                    minDist = distJI
                    minIndex = j

            # 样本上次分配结果跟本次不一样，标志位clusterChanged置True
            if clusterAssment[i, 0] != minIndex:
                clusterChanged = True
            clusterAssment[i, :] = minIndex, minDist ** 2  # 分配样本到最近的簇

        iterN += 1
        sse = sum(clusterAssment[:, 1])
        print('the SSE of %d' % iterN + 'th iteration is %f' % sse)

        # step3:更新聚类中心
        for cent in range(k):  # 样本分配结束后，重新计算聚类中心
            ptsInClust = X[clusterAssment[:, 0] == cent, :]
            centroids[cent, :] = np.mean(ptsInClust, axis=0)

        # 如果聚类重心没有发生改变，则退出迭代
        if not clusterChanged:
            break

    return centroids, clusterAssment


# 进行k-means聚类
k = 2  # 用户定义聚类数
mycentroids, clusterAssment = kmeans(X, k)

x1 = np.zeros((400, 1))
x2 = np.zeros((400, 1))
for i in range(400):
    x1[i] = np.cos(X[i, 0]) * X[i, 1]
    x2[i] = np.sin(X[i, 0]) * X[i, 1]
X = np.c_[x1, x2]


def datashow(dataSet, k, centroids, clusterAssment):  # 二维空间显示聚类结果
    from matplotlib import pyplot as plt
    num, dim = np.shape(dataSet)  # 样本数num ,维数dim

    if dim != 2:
        print('sorry,the dimension of your dataset is not 2!')
        return 1
    marksamples = ['or', 'ob', 'og', 'ok', '^r', '^b', '<g']  # 样本图形标记
    if k > len(marksamples):
        print('sorry,your k is too large,please add length of the marksample!')
        return 1
        # 绘所有样本
    for i in range(num):
        markindex = int(clusterAssment[i, 0])  # 矩阵形式转为int值, 簇序号
        # 特征维对应坐标轴x,y；样本图形标记及大小
        plt.plot(dataSet[i, 0], dataSet[i, 1], marksamples[markindex], markersize=6)

    # 绘中心点
    markcentroids = ['o', '*', '^']  # 聚类中心图形标记
    label = ['0', '1', '2']
    c = ['yellow', 'pink', 'red']
    for i in range(k):
        plt.plot(centroids[i, 0], centroids[i, 1], markcentroids[i], markersize=15, label=label[i], c=c[i])
        plt.legend(loc='upper left')  # 图例
    plt.xlabel('feature 1')
    plt.ylabel('feature 2')

    plt.title('k-means cluster result')  # 标题
    plt.show()


# 画出实际图像
def trgartshow(dataSet, k, labels):
    from matplotlib import pyplot as plt

    num, dim = np.shape(dataSet)
    label = ['0', '1', '2']
    marksamples = ['ob', 'or', 'og', 'ok', '^r', '^b', '<g']
    # 通过循环的方式，完成分组散点图的绘制
    for i in range(num):
        plt.plot(dataSet[i, 0], dataSet[i, 1], marksamples[int(labels[i])], markersize=6)

    # 添加轴标签和标题
    plt.xlabel('feature 1')
    plt.ylabel('feature 2')
    plt.title('true result')  # 标题

    # 显示图形
    plt.show()
    # label=labels.iat[i,0]


# 绘图显示
datashow(X, k, mycentroids, clusterAssment)
trgartshow(X, 3, y)